<script setup lang="ts">

import {ref, onMounted, reactive} from "vue"
import * as echarts from "echarts";
import {getCustomerAnalysisDataApi} from "@/api/customer/dashboard";
import {CopyToClipboard} from "@/utils";


const customerData = reactive({
  customerType: [],
  maintenanceNum: [],
  maintenanceType: [],
  licenseNum: [],
  vipLevel: {
    xAxisData: [],
    seriesData: [],
    sourceData: []
  },
  env: {
    xAxisData: [],
    seriesData: [],
    sourceData: []
  },
  describeInfo: []
})


const loading = ref(false)
const customerType = ref(null);
const maintenanceNum = ref(null);
const maintenanceType = ref(null);
const licenseNum = ref(null);
const vipLevelNum = ref(null);
const envNum = ref(null);

let customerTypeChart: echarts.ECharts;
let maintenanceNumChart: echarts.ECharts;
let maintenanceTypeChart: echarts.ECharts;
let licenseNumChart: echarts.ECharts;
let vipLevelNumChart: echarts.ECharts;
let envNumChart: echarts.ECharts;
let option: echarts.EChartsOption;

function renderChart() {

  // 客户类型分析图表
  if (customerType.value) {
    option = {
      title: {
        text: '客户类型分析',
        subtext: '包含所有客户',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}  <br/> 占比: {d}%'
      },
      legend: {
        top: 'bottom',
      },
      series: [
        {
          name: '客户类型',
          type: 'pie',
          radius: ['35%', '60%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 25,
              // fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: customerData.customerType
        }
      ]
    };
    option && customerTypeChart.setOption(option);
  }


  // 维保数量统计
  if (maintenanceNum.value) {
    option = {
      title: {
        text: '维保数量分析',
        subtext: '不包含POC客户',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}  <br/> 占比: {d}%'
      },
      legend: {
        top: 'bottom',
      },
      series: [
        {
          name: '维保类型',
          type: 'pie',
          radius: ['35%', '60%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 25,
            }
          },
          labelLine: {
            show: false
          },
          data: customerData.maintenanceNum
        }
      ]
    };
    option && maintenanceNumChart.setOption(option);
  }


  // 维保类型分析
  if (maintenanceNum.value) {
    option = {
      title: {
        text: '维保类型分析',
        subtext: '仅统计维保期内',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}  <br/> 占比: {d}%'
      },
      legend: {
        top: 'bottom',
      },
      series: [
        {
          name: '维保类型',
          type: 'pie',
          radius: ['35%', '60%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 25,
            }
          },
          labelLine: {
            show: false
          },
          data: customerData.maintenanceType
        }
      ]
    };
    option && maintenanceTypeChart.setOption(option);
  }

  // Licese数量分析
  if (licenseNum.value) {
    option = {
      title: {
        text: 'License数量分析',
        subtext: '所有客户',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}  <br/> 占比: {d}%'
      },
      legend: {
        top: 'bottom',
      },
      series: [
        {
          name: 'license数量',
          type: 'pie',
          radius: ['35%', '60%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 25,
            }
          },
          labelLine: {
            show: false
          },
          data: customerData.licenseNum
        }
      ]
    };
    option && licenseNumChart.setOption(option);
  }

  // 客户等级分析 vipLevelNum
  if (vipLevelNum.value) {
    option = {
      title: {
        text: '客户VIP等级分析',
        subtext: '仅统计维保期内',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: customerData.vipLevel.xAxisData,
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '数量',
          type: 'bar',
          barWidth: '30%',
          data: customerData.vipLevel.seriesData
        }
      ]
    };
    option && vipLevelNumChart.setOption(option);
  }


  // 环境数量分析 envNum
  if (envNum.value) {
    option = {
      title: {
        text: '环境数量分析',
        subtext: '包含所有客户',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: customerData.env.xAxisData,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            rotate: 45    // 设置标签旋转角度为45度
          }
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '数量',
          type: 'bar',
          barWidth: '30%',
          data: customerData.env.seriesData
        }
      ]
    };
    option && envNumChart.setOption(option);
  }
}


/** 处理客户分析仪表盘所需的数据 */
function analysisCustomerData(res: any) {
  customerData.customerType = res.customerType
  customerData.maintenanceNum = res.maintenanceNum
  customerData.maintenanceType = res.maintenanceType
  customerData.licenseNum = res.license

  const vipLevel = res.vipLevel
  customerData.vipLevel.sourceData = vipLevel
  for (let i = 0; i < vipLevel.length; i++) {
    customerData.vipLevel.xAxisData.push(vipLevel[i].name)
    customerData.vipLevel.seriesData.push(vipLevel[i].value)
  }

  const env = res.env
  customerData.env.sourceData = env
  for (let i = 0; i < env.length; i++) {
    customerData.env.xAxisData.push(env[i].name)
    customerData.env.seriesData.push(env[i].value)
  }

  // 处理表格需要的数据
  customerData.describeInfo = [
    {
      category: "客户类型",
      subCategory: customerData.customerType
    },
    {
      category: "维保数量分析",
      subCategory: customerData.maintenanceNum
    },
    {
      category: "维保类型分析",
      subCategory: customerData.maintenanceType
    },
    {
      category: "VIP等级分析",
      subCategory: customerData.vipLevel.sourceData
    },
    {
      category: "环境数量分析",
      subCategory: customerData.env.sourceData
    },
  ]
}

async function fetchCustomerData() {
  loading.value = true
  try {
    const res = await getCustomerAnalysisDataApi()
    if (res) {

      // 处理仪表盘所需数据
      analysisCustomerData(res.data.list)
      // 渲染echart
      renderChart()
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}


/** 拷贝源数据 */
function copySourceData() {
  const text = JSON.stringify(customerData.describeInfo, null, 2)
  CopyToClipboard(text)
}

onMounted(async () => {
  customerTypeChart = echarts.init(customerType.value);
  maintenanceNumChart = echarts.init(maintenanceNum.value);
  maintenanceTypeChart = echarts.init(maintenanceType.value);
  licenseNumChart = echarts.init(licenseNum.value);
  vipLevelNumChart = echarts.init(vipLevelNum.value);
  envNumChart = echarts.init(envNum.value);
  await fetchCustomerData(); // 获取后端数据
});
</script>

<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>客户数据分析</span>
        <el-button icon="CopyDocument" type="primary" link
                   @click="copySourceData()"
        >复制源数据
        </el-button>
      </div>
    </template>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover">
          <div ref="customerType" style="width: 100%; height: 300px;" v-loading="loading"/>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div ref="maintenanceNum" style="width: 100%; height: 300px;" v-loading="loading"/>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div ref="maintenanceType" style="width: 100%; height: 300px;" v-loading="loading"/>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div ref="licenseNum" style="width: 100%; height: 300px;" v-loading="loading"/>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="6">
        <el-card shadow="hover">
          <div ref="vipLevelNum" style="width: 100%; height: 300px;" v-loading="loading"/>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="hover">
          <div ref="envNum" style="width: 100%; height: 300px;" v-loading="loading"/>
        </el-card>
      </el-col>

      <el-col :span="10">
        <div>
          <el-tabs type="border-card" style="height: 340px;" v-loading="loading">
            <template v-for="item in customerData.describeInfo">
              <el-tab-pane :label="item.category">
                <el-tabs tab-position="left" style="height: 270px">
                  <template v-for="subItem in item.subCategory">
                    <el-tab-pane :label="subItem.name">
                      <el-table :data="subItem.list"
                                height="270px"
                                max-height="270px"
                                :show-header="false"
                                :cell-style="{ textAlign: 'center' }"
                      >
                        <el-table-column prop="name"></el-table-column>
                        <el-table-column v-if="item.category === '环境数量分析'" prop="version"></el-table-column>
                      </el-table>
                    </el-tab-pane>
                  </template>
                </el-tabs>
              </el-tab-pane>
            </template>


          </el-tabs>
        </div>
      </el-col>
    </el-row>
  </el-card>
</template>

<style scoped lang="scss">

.summaryCard span {
  margin-left: 20px; /* 调整文字与图片之间的间距 */
}

.summaryCard img {
  width: 100px; /* 设置图片宽度 */
  height: 40px; /* 设置图片高度 */
  float: right
}
</style>
